#!/usr/bin/python
# -*- coding:utf-8 -*-

import platform
import threading
import time
import sys
import os
import urllib
import re
import codecs
import shutil
import logging
import importlib
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys #导入模拟点击

# importlib.reload(sys)
sys.path.append('../')

from base import utils
# sys.setdefaultencoding("utf-8")

def __get_browser():
    try:
        # dcap = dict(DesiredCapabilities.PHANTOMJS)  #设置userAgent
        # dcap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (X11; CrOS i686 4319.74.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36")

        options = webdriver.ChromeOptions()
        #options.binary_location("")
        options._binary_location = 'C:\Users\duye\AppData\Local\Google\Chrome\Application\chrome.exe'
        options.add_argument('lang=zh_CN.UTF-8')
        # options.add_argument('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/535.11')

        # profile = {"plugins.plugins_enabled": ['Chrome PDF Viewer'],
        #           "plugins.plugins_enabled": ['Adobe Flash Player'],
        #           "profile.managed_default_content_settings.images": 1,
         #          "profile.default_content_settings.popups": 0}
        #options.add_experimental_option("prefs", profile)
        options.add_argument('--start-maximized')
        options.add_argument('--enable-profile-shortcut-manager')
        options.add_argument("user-data-dir=C:\Users\duye\AppData\Local\Google\Chrome\User Data\Default")
        sysstr = platform.system()
        if sysstr == "Windows":
            browser = webdriver.PhantomJS(executable_path='C:\Python27\Scripts\phantomjs.exe')
            # browser = webdriver.PhantomJS()
            # browser = webdriver.Chrome(chrome_options=options)
        else:
            browser = webdriver.Chrome(chrome_options=options)
            # browser = webdriver.PhantomJS('phantomjs')

        browser.implicitly_wait(30)  ##设置超时时间
        browser.set_page_load_timeout(30)  ##设置超时时间
        browser.maximize_window()  # 设置全屏
        #browser.set_window_rect(100, 100, 400, 400)
        return browser
    except Exception as e:
        logging.error("failed: %s" % (e))
        return False

def download(url):
    # find file id
    # search_obj = re.search(r'(http://www.docin.com/p-)(.*?)(.html)', url, re.I)
    # if search_obj:
    #     file_id = search_obj.group(2)
    # else:
    #     logging.error("get file id failed from url:%s" % url)
    #     return False

    # create directory
    # try:
    #     if os.path.exists(file_id):
    #         shutil.rmtree(file_id)
    #     os.mkdir(file_id)
    # except Exception as e:
    #     logging.error("failed: %s" % (e))
    #     return False

    # cut file image
    browser = __get_browser()
    try:
        browser.get(url)
        browser.execute_script("""
            (function () {
                var y = 0;
                var step = 100;
                window.scroll(0, 0);

                function f() {
                    if (y < document.body.scrollHeight) {
                        y += step;
                        window.scroll(0, y);
                        setTimeout(f, 100);
                    } else {
                        window.scroll(0, 0);
                        document.title += "scroll-done";
                    }
                }

                setTimeout(f, 1000);
            })();
        """)
        #time.sleep(6)
        #browser.find_element_by_xpath('// *[ @ id = "unFlashTips"] / a').click()
        #time.sleep(3)
        browser.save_screenshot(file_id + '/open.png')
    except Exception as e:
        logging.error("failed: %s" % (e))
        return False

    browser.quit()

if __name__ == "__main__":
    # download("https://wenku.baidu.com/view/443fa25c804d2b160b4ec01f.html?sxts=1525673013039")
    download('https://www.docin.com/p-277979687.html')